<script setup>
import { onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { AxiosError } from 'axios';
import authService from "@/services/auth.service";
import personalCenterService from "@/services/personal-center.service";
import { useAuthStore } from '@/stores/auth';
import { showFailToast, showNotify } from 'vant';
import { REGEX_EMAIL, REGEX_PASSWORD, REGEX_PHONE } from "@/utils/regexes";

const router = useRouter();
const authStore = useAuthStore();

const entity = ref({});
const verifyCodeUrl = ref("");
const formRef = ref();
const loading = ref(false);

const rules = reactive({
    username: [
        {
            required: true,
            message: '请输入用户名',
        },
        {
            validator: async (value) => {
                if (!value) {
                    return true;
                }
                const res = await authService.checkUsername(value);
                return res.data.data;
            },
            message: "用户名已存在"
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
        },
        {
            validator: (value) => {
                return REGEX_PASSWORD.test(value);
            },
            message: "密码格式应为8-18位数字、字母、符号的任意两种组合",
        },
    ],
    confirmPassword: [
        {
            required: true,
            message: '请输入确认密码',
        },
        {
            validator: async (value) => {
                if (entity.value.password && entity.value.confirmPassword && entity.value.password != entity.value.confirmPassword) {
                    return false;
                }
                return true;
            },
            message: "两次密码输入不一致",
        }
    ],
    phone: [
        {
            required: true,
            message: '请输入手机号',
        },
        {
            validator: (value) => {
                return REGEX_PHONE.test(value);
            },
            message: "手机号格式不正确",
        }, ,
        {
            validator: async (value) => {
                if (!value) {
                    return true;
                }
                const res = await authService.checkPhone(value);
                return res.data.data;
            },
            message: "手机号已存在"
        }
    ],
    email: [
        {
            required: true,
            message: '请输入邮箱',
        },
        {
            validator: (value) => {
                return REGEX_EMAIL.test(value);
            },
            message: "邮箱格式不正确",
        },
        {
            validator: async (value) => {
                if (!value) {
                    return true;
                }
                const res = await authService.checkEmail(value);
                return res.data.data;
            },
            message: "邮箱已存在"
        }
    ],
    verifyCode: [
        {
            required: true,
            message: '请输入验证码',
        },
    ],
});

onMounted(async () => {
    updateVerifyCode();

    load();
});

const updateVerifyCode = async () => {
    const res = await authService.getVerifyCode();
    verifyCodeUrl.value = `${res.data.data?.image}`;
    entity.value.verifyCodeKey = res.data.data?.key;
}

const load = async () => {

}


const login = async () => {
    router.push("/login");
};


const register = async () => {
    const formEl = formRef.value;
    loading.value = true;
    if (!formEl) {
        loading.value = false;
        return;
    }
    try {
        await formEl.validate();

        const res = await authService.register(entity.value);
        showNotify({ message: "注册成功", type: "success" });
        router.push("/login");
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            showFailToast(msg);
        }
        updateVerifyCode();
        throw err;
    } finally {
        loading.value = false;
    }
}

</script>

<template>
    <div class="h-full w-full top-0 left-0 absolute flex flex-col justify-center register-form-container">
        <VanForm ref="formRef" class="login-form" validate-trigger="onBlur">
            <div class="w-full flex flex-row justify-center login-form-logo-container">
                <img class="register-form-logo" src="@/assets/logo.svg" />
            </div>
            <h3 class="text-center">注册新用户</h3>
            <VanCellGroup inset>
                <VanField v-model:model-value="entity.username" name="username" label="用户名" placeholder="用户名"
                    :rules="rules.username">
                </VanField>
                <VanField v-model:model-value="entity.password" type="password" name="password" label="密码" placeholder="密码"
                    :rules="rules.password">
                </VanField>
                <VanField v-model:model-value="entity.confirmPassword" type="password" name="confirmPassword" label="确认密码"
                    placeholder="确认密码" :rules="rules.confirmPassword">
                </VanField>
                <VanField v-model:model-value="entity.phone" name="phone" label="手机号" placeholder="手机号"
                    :rules="rules.phone">
                </VanField>
                <VanField v-model:model-value="entity.email" name="email" label="邮箱" placeholder="邮箱" :rules="rules.email">
                </VanField>
                <VanField class="" v-model:model-value="entity.verifyCode" name="verifyCode" label="验证码" placeholder="验证码"
                    :rules="rules.verifyCode">
                    <template #button>
                        <img :src="verifyCodeUrl" class="verify-code" @click="updateVerifyCode()" />
                    </template>
                </VanField>
            </VanCellGroup>
            <VanCellGroup inset>
                <VanButton round block type="primary" @click="register">
                    注册
                </VanButton>
                <VanButton class="mt-2" round block @click="login">
                    已有账号，返回登录
                </VanButton>
            </VanCellGroup>
        </VanForm>
    </div>
</template>

<style lang="scss" scoped>
.register-form-container {
    .register-form-logo {
        height: 64px;
    }

    .verify-code {
        height: 40px;
    }
}
</style>